package com.codeyang.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.codeyang.constant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * 描述:  使用代码方式 配置security的路由
 *
 * @author CodeYang_Site
 * @version 2021/5/22 19:42
 */
@Configuration
public class LoginRouteConfig {

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 给授权专门做的存入token路由
     * 设置网关请求回来时的走这里,如果是 /oauth/token 就存储token
     *
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        RouteLocator build = builder.routes()
                //配置 生产token存入redis
                .route("oauth-route-id", r -> r.path("/oauth/token").filters(
                        f -> f.modifyResponseBody(String.class, String.class, (exchange, s) -> {
                            // 存储token
                            JSONObject jsonObject = JSON.parseObject(s);
                            //     如果包含access_token就放进redis里面
                            String accessToken = jsonObject.getString("access_token");
                            if (StringUtils.hasText(accessToken)) {
                                // 拿到过期时间
                                Long expiresIn = jsonObject.getLong("expires_in");
                                // 存入redis
                                redisTemplate.opsForValue().set(GatewayConstant.OAUTH_JWT_PREFIX + accessToken, "", Duration.ofSeconds(expiresIn));
                            }
                            return Mono.just(s);
                        })).uri("lb://auth-server"))
                .build();
        return build;
    }
}
